package com.haiheng.module_main.mode

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.haiheng.common.api.API
import com.haiheng.common.constant.AppConstant
import com.haiheng.common.constant.RourePage
import com.haiheng.library.log.LogUtils
import com.haiheng.library.log.LogWriter
import com.haiheng.library_base.db.BookInfoSub
import com.haiheng.library_base.db.BookShiftingRecordTable
import com.haiheng.library_base.db.KV
import com.haiheng.library_base.db.KVDatabase
import com.haiheng.library_base.db.LayerMap
import com.haiheng.library_base.db.RecordTable
import com.haiheng.library_base.db.SmartEploymentRecordTable
import com.haiheng.library_base.http.Domain
import com.haiheng.library_base.http.HttpRequest
import com.haiheng.library_base.http.HttpResponse
import com.haiheng.library_base.http.api
import com.haiheng.library_base.http.postJson
import com.haiheng.library_base.model.BaseViewModel
import com.haiheng.module_main.bean.req.Asset
import com.haiheng.module_main.bean.req.BookAssetLocationReq
import com.haiheng.module_main.bean.req.BookShiftingReq
import com.haiheng.module_main.bean.req.LayLocationInfo
import com.haiheng.module_main.bean.req.OnselfByCallNumberReq
import com.haiheng.module_main.bean.req.ShiftingInfo
import com.haiheng.module_main.bean.req.SourceInfo
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import okhttp3.internal.notifyAll
import java.lang.Exception

/**
 *
 * @Des:上架，倒架
 * @Author: hwz
 * @Date:2023/6/15 0015
 * @Version: 1.0
 */
class DeploymentViewModel(private val bookInfoViewModel: BookInfoViewModel) : BaseViewModel() {

    var startCallNu = MutableLiveData<String>()
    var endCallNu = MutableLiveData<String>()

    /**
     * 本地单册上架
     *
     * @param outLayNo
     * @param assets
     */
    fun bookAssetLocationByOffLine(outLayNo:String,assets: List<Asset>){
        viewModelScope.launch(Dispatchers.IO) {
            try {

                assets.forEach {
                    var record = RecordTable()
                    record.barCode = it.barCode
                    record.currentPlaceIndex = it.currentPlaceIndex
                    record.recordType = RourePage.SINGLE_VOLUME_DEPLOYMENT.name
                    record.outLayNo = outLayNo
                    record.locationType = 3

                    bookInfoViewModel.bookListData.value?.forEach {
                        it.fixedContainerSub?.name = bookInfoViewModel.layerInfo?.value?.name
                    }
                    var bookInfoBean = KVDatabase.getDb().bookInfoDao().getBookInfoByBarCode(it.barCode)
                    if (bookInfoBean != null){
                        var lay = KVDatabase.getDb().getLayerMap().queryByOutValue(outLayNo)
                        if (lay.name.equals(bookInfoBean.fixedContainerSub.name)){
                            bookInfoBean.bookOnShelfStatus = 1
                        }else{
                            bookInfoBean.bookOnShelfStatus = 2
                        }
                        bookInfoBean.fixedContainerSub.name = bookInfoViewModel.layerInfo?.value?.name
                    }
                    KVDatabase.getDb().bookInfoDao().updateBookInfo(bookInfoBean)
                    KVDatabase.getDb().getRecordDao().insert(record)
                    bookInfoViewModel._bookListData.postValue(bookInfoViewModel.bookListData.value)
                    LogWriter.e("本地上架成功")
                    bookInfoViewModel.showMsg.postValue("本地上架成功")
                }
            }catch (ex:Exception){
                bookInfoViewModel.showMsg.postValue("本地上架异常："+ex.toString())
                LogWriter.e("本地上传失败：${ex}")
            }


        }
    }

    /**
     * 上架/倒架
     *
     * @param outLayNo 物理层架号
     */
    fun bookAssetLocation(outLayNo:String) {
        var assets = arrayListOf<Asset>()
        bookInfoViewModel.bookListData.value?.forEachIndexed { index, value ->
            LogUtils.e("索引 ${index} 的值为 ${value}")
            if (value.isSelect){
                var asset = Asset()
                asset.barCode = value.barCode.toString()
                asset.currentPlaceIndex = index
                assets.add(asset)
            }
        }
        if (assets == null || assets.size < 1){
            bookInfoViewModel.showMsg.postValue("没有选择对应上架书籍")
        }
        if (AppConstant.isOpenOfflineMode()){
            bookAssetLocationByOffLine(outLayNo,assets)
            return
        }
        var bookAssetLocationReq = BookAssetLocationReq()
        var layLocationInfos = arrayListOf<LayLocationInfo>()
        var layLocationInfo = LayLocationInfo()
        layLocationInfo.outLayNo = outLayNo//真实层架号
        layLocationInfo.containerIdType = 4 //4为真实层架号  5为rfid智能书架层架号 0系统层ID

        layLocationInfo.assets = assets
        layLocationInfos.add(layLocationInfo)
        bookAssetLocationReq.layLocationInfos  = layLocationInfos
        var sourceInfo = SourceInfo()
        sourceInfo.orgCode = AppConstant.getLibraryCode()
        sourceInfo.dataSourceId = AppConstant.getMachineUuid()
        sourceInfo.dataSourceType = "6" //数据起源  1盘点  2自动盘点  3条码绑定  4走接口上传   5内部联动  6手持 7盘点车
        sourceInfo.deviceMac = AppConstant.getMachineUuid()
        sourceInfo.locationType = 3 //1 整层盘点(如不在本次列表会离架)    2 单一上架   3整层上架（不阅读）
        bookAssetLocationReq.sourceInfo = sourceInfo
        viewModelScope.launch {
            val request = HttpRequest(API.PATH.BOOK_ASSET_LOCATION)
                .putHeader(Domain.KEY_NAME,Domain.VALUE_DEFUlT)
                .putHeader(API.PARAM.PARAM_HEADER_TOKEN,AppConstant.getToken())
                .setJsonObjec(bookAssetLocationReq)
            var response  = postJson<HttpResponse>(request)
            if (response.isSuccess == true){
                bookInfoViewModel.showMsg.postValue(response.message)
                //更新页面显示位置信息
                bookInfoViewModel.bookListData.value?.forEach {
                    it.fixedContainerSub?.name = bookInfoViewModel.layerInfo?.value?.name
                }
                bookInfoViewModel._bookListData.postValue(bookInfoViewModel.bookListData.value)
                LogUtils.e("上架成功：${response.toJson()}")
            }else{
                bookInfoViewModel.showMsg.postValue(response.errorMsg)
                LogWriter.w("上架信息失败:${response.toJson()}")
            }

        }
    }

    /**
     * 整层离线倒架
     *
     * @param srcContainerSubId
     * @param newContainerSubId
     */
    fun bookShiftingByOfflineMode(srcContainerSubId:Int,newContainerSubId:Int) {
        viewModelScope.launch(Dispatchers.IO) {
            try {
                var db = KVDatabase.getDb()
                val bookInfoDao = db.bookInfoDao()
                val recordDao = db.getBookShiftingRecordDao()
                //整层倒架，把目标层架原来书下架，
                var srcList  =  bookInfoDao.getBookInfoByfixedContainerSubId(srcContainerSubId)
                var newList  =  bookInfoDao.getBookInfoByfixedContainerSubId(newContainerSubId)
                var srcLay = srcList.first().fixedContainerSub
                var newLay = newList.first().fixedContainerSub
                srcList.forEach {
                    it.fixedContainerSub = newLay
                    it.currentContainerSub = newLay
                    it.fixedContainerSubId = newContainerSubId
                    it.currentContainerSubId = newContainerSubId
                }
                newList.forEach {
                    it.currentPlaceIndex = 0
                    it.currentContainerSub = BookInfoSub()
                }
                bookInfoDao.updateBookInfo(*srcList.toTypedArray())
                bookInfoDao.updateBookInfo(*newList.toTypedArray())
                var bookShiftingRecordTable = BookShiftingRecordTable()
                bookShiftingRecordTable.recordType = RourePage.BOOK_OFF_SHELVING.name
                bookShiftingRecordTable.srcContainerSubId = srcContainerSubId
                bookShiftingRecordTable.newContainerSubId = newContainerSubId
                bookShiftingRecordTable.orgCode = AppConstant.getLibraryCode()
               var result =  recordDao.insert(bookShiftingRecordTable)
                if (result > 0){
                    bookInfoViewModel.showMsg.postValue("本地整层倒架成功")
//                    bookInfoViewModel.bookListData.value?.forEach {
//                        it.fixedContainerSub?.name = bookInfoViewModel.layerInfo?.value?.name.toString()
//                    }
//                    bookInfoViewModel._bookListData.postValue(bookInfoViewModel.bookListData.value)
                    LogUtils.e("本地整层倒架成功")
                }else{
                    bookInfoViewModel.showMsg.postValue("本地整层倒架失败")
                    LogWriter.e("本地整层倒架失败：${result}")
                }
            }catch (ex:Exception){
                bookInfoViewModel.showMsg.postValue("本地整层倒架异常：${ex}")
                LogWriter.e("本地整层倒架异常：${ex}")
            }

        }
    }

    /**
     * 整层倒架
     *
     * @param srcContainerSubId 来源位置
     * @param newContainerSubId 目标位置
     */
    fun bookShifting(srcContainerSubId:Int,newContainerSubId:Int) {
        if (AppConstant.isOpenOfflineMode()){
            bookShiftingByOfflineMode(srcContainerSubId,newContainerSubId)
            return
        }
        var req = BookShiftingReq()
        req.orgCode = AppConstant.getLibraryCode()
        var shiftingInfos = arrayListOf<ShiftingInfo>()
        var shiftingInfo = ShiftingInfo()
        shiftingInfo.newContainerSubId = newContainerSubId
        shiftingInfo.srcContainerSubId = srcContainerSubId
        shiftingInfos.add(shiftingInfo)
        req.shiftingInfos = shiftingInfos
        viewModelScope.launch {
            val request = HttpRequest(API.PATH.BOOK_SHIFTING)
                .putHeader(Domain.KEY_NAME,Domain.VALUE_DEFUlT)
                .putHeader(API.PARAM.PARAM_HEADER_TOKEN,AppConstant.getToken())
                .setJsonObjec(req)
            var response  = postJson<HttpResponse>(request)
            if (response.isSuccess == true){
                bookInfoViewModel.showMsg.postValue(response.message)
//                bookInfoViewModel.bookListData.value?.forEach {
//                    it.fixedContainerSub?.name = bookInfoViewModel.layerInfo?.value?.name.toString()
//                }
//                bookInfoViewModel._bookListData.postValue(bookInfoViewModel.bookListData.value)
                LogUtils.e("倒架成功：${response.toJson()}")
            }else{
                bookInfoViewModel.showMsg.postValue(response.errorMsg)
                LogUtils.w("倒架失败:${response.toJson()}")
            }
        }
    }

    /**
     * 智慧上架，根据层架标可以选择按层还是书架号上架
     *
     * @param shelfNo
     * @param onSelfObjType
     */
    fun onSelfByCallNumber(shelfNo:String,onSelfObjType:Int){
        if (AppConstant.isOpenOfflineMode()){
            onShelfByCallNumberByOffline(shelfNo,onSelfObjType)
            return
        }
        var req = OnselfByCallNumberReq()
        req.orgCode = AppConstant.getLibraryCode()
        req.onSelfObjNo = shelfNo         //上架目标编号  书架层号 或  书架号(真实物理层架号)
        req.onSelfObjType = onSelfObjType //上架目标类型  0书架层号  1书架号
        req.startCallNu = startCallNu.value.toString()
        req.endCallNu = endCallNu.value.toString()
        req.logUser = AppConstant.getMachineUuid()
        api {
            val request = HttpRequest(API.PATH.ONSELF_BY_CALLNUMBER)
                .putHeader(Domain.KEY_NAME, Domain.VALUE_DEFUlT)
                .putHeader(API.PARAM.PARAM_HEADER_TOKEN,AppConstant.getToken())
                .setJsonObjec(req)
            var response = postJson<HttpResponse>(request)
            if (response.isSuccess == true){
                bookInfoViewModel.showMsg.postValue(response.message)
                LogUtils.e("上架成功：${response.toJson()}")
            }else{
                bookInfoViewModel.showMsg.postValue(response.errorMsg)
                LogUtils.w("上架信息失败:${response.toJson()}")
            }

        }
    }

    fun onShelfByCallNumberByOffline(shelfNo:String,onSelfObjType:Int){
        api {
           var smartDao = KVDatabase.getDb().getSmartEploymentRecordDao()
            var s = SmartEploymentRecordTable()
            s.recordType = RourePage.SMART_DEPLOYMENT.name
            s.onSelfObjNo =shelfNo
            s.onSelfObjType = onSelfObjType
            s.startCallNu = startCallNu.value.toString()
            s.endCallNu = endCallNu.value.toString()
            s.logUser = AppConstant.getMachineUuid()
            s.orgCode = AppConstant.getLibraryCode()
            var result = smartDao.insert(s)
            if (result>0){
                bookInfoViewModel.showMsg.postValue("本地上架成功")
                LogUtils.e("本地上架成功")
            }else{
                bookInfoViewModel.showMsg.postValue("本地上架失败")
                LogUtils.w("本地上架失败")
            }
        }
    }
}